package com.ruoyi.common.utils.sign;

import com.ruoyi.common.utils.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    private static String vectorKey = "yoosoft@hubelf@#";

    private static String slatKey = "hubelf@202312108";

    public static void main(String[] args){
        /*
        String data = "Hello, world!";
        String enc = encrypt(data);
        System.out.println(enc);
        System.out.println(decrypt(data));

         */
    }

    public static String encrypt(String content){
        try {
            if (StringUtils.isEmpty(content)) return content;
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] encrypted = cipher.doFinal(content.getBytes());
            return Base64.encode(encrypted);
        }catch (Exception e){
            e.printStackTrace();
        }
        return content;
    }

    public static String decrypt(String base64Content){
        try {
            if (StringUtils.isEmpty(base64Content)) return base64Content;
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            byte[] content = Base64.decode(base64Content);
            byte[] encrypted = cipher.doFinal(content);
            return new String(encrypted);
        }catch (Exception e){
            e.printStackTrace();
        }
        return base64Content;
    }
}
